import 'package:dio/dio.dart';
import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:sui_shou_pai/Utils/storage_util.dart';
import 'package:sui_shou_pai/chat/chat_records_list.dart';
import 'package:sui_shou_pai/chat/entity/chat_record.dart';
import 'package:sui_shou_pai/chat/entity/global.dart';
import 'package:sui_shou_pai/module/color.dart';
import 'package:sui_shou_pai/module/effect.dart';
import 'package:sui_shou_pai/network/http_config.dart';
import 'package:sui_shou_pai/network/http_request.dart';

class ChatRoom extends StatefulWidget {
  final String id;

  final String name;

  final String avatar;

  const ChatRoom(
      {Key key, @required this.id, @required this.name, @required this.avatar})
      : super(key: key);

  @override
  _ChatRoomState createState() => _ChatRoomState();
}

class _ChatRoomState extends State<ChatRoom> {
  bool emojiShowing = false;

  GlobalKey<ChatRecordsListState> textKey = GlobalKey(); //设置key,绑定待刷新控件.

  //输入框的焦点控制
  FocusNode _contentFocusNode = new FocusNode();

  //输入框控制器
  TextEditingController _contentController = new TextEditingController();

  /**
   * 发送信息
   */
  Future<void> addRecord(String content) async {
    _contentController.clear(); //清空输入框
    // BaseOptions options =
    //     new BaseOptions(baseUrl: BASE_URL, connectTimeout: 50000);
    // Dio dio = new Dio(options);
    // var response = await dio.post("/chat-record/saveOne", data: {
    //   "createTime": Global.currentTimeMillis(),
    //   "updateTime": Global.currentTimeMillis(),
    //   "time": Global.currentTimeMillis(),
    //   "senderId": Global.me,
    //   "receiverId": widget.id,
    //   "content": content,
    //   "isRead": "0"
    // });

    HttpRequest.request("$BASE_URL/chat-record/saveOne",
            method: "post",
            data: {
              "createTime": Global.currentTimeMillis(),
              "updateTime": Global.currentTimeMillis(),
              "time": Global.currentTimeMillis(),
              "senderId": Global.me,
              "receiverId": widget.id,
              "content": content,
              "isRead": "0"
            },
            token: await StorageUtil.getStringItem("token"))
        .then((value) {
      ChatRecord record = new ChatRecord("0", Global.me, widget.id.toString(),
          content, Global.currentTimeMillis(), "0");
      String result = value.data["message"];
      if (result == "发送成功") {
        textKey.currentState.click(record); //刷新列表
      } else {
        Fluttertoast.showToast(msg: "发送失败，请重试！");
      }
    });
  }

  @override
  void setState(VoidCallback fn) {
    // TODO: implement setState
    super.setState(fn);
  }

  _onEmojiSelected(Emoji emoji) {
    _contentController
      ..text += emoji.emoji
      ..selection = TextSelection.fromPosition(
          TextPosition(offset: _contentController.text.length));
  }

  _onBackspacePressed() {
    _contentController
      ..text = _contentController.text.characters.skipLast(1).toString()
      ..selection = TextSelection.fromPosition(
          TextPosition(offset: _contentController.text.length));
  }

  void hindKeyBoarder() {
    //输入框失去焦点
    _contentFocusNode.unfocus();
    //隐藏键盘
    SystemChannels.textInput.invokeMethod('TextInput.hide');
  }

  void hindEmoji() {
    //隐藏表情包
    setState(() {
      emojiShowing = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          hindKeyBoarder();
          hindEmoji();
        }, //点击事件
        child: Scaffold(
          appBar: AppBar(
            foregroundColor: greyF3F3F3,
            backgroundColor: greyF3F3F3,
            elevation: 0,
            title: Text(
              widget.name,
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            centerTitle: true,
          ),
          body: buildEditWidget(),
        ));
  }

  /**
   * body
   */
  Widget buildEditWidget() {
    return Column(
      children: <Widget>[
        Expanded(
          child: Container(
            alignment: Alignment.topCenter,
            color: greyF3F3F3,
            child: ChatRecordsList(
              id: widget.id,
              avatar: widget.avatar,
              key: textKey,
            ),
          ),
        ),
        Row(
          children: <Widget>[
            Expanded(
              child: Container(
                padding: EdgeInsets.fromLTRB(18, 12, 0, 12),
                child: ClipRRect(
                  borderRadius: borderRadiusAll4(),
                  child: TextField(
                    focusNode: _contentFocusNode,
                    controller: _contentController,
                    style: TextStyle(
                      fontSize: 18,
                    ),
                    decoration: InputDecoration(
                      isCollapsed: true,
                      contentPadding: EdgeInsets.symmetric(
                          vertical: 10.0, horizontal: 12.0),
                      fillColor: greyF3F3F3,
                      filled: true,
                      border: InputBorder.none,
                    ),
                    cursorColor: greyCCCCCC,
                    maxLines: 5,
                    minLines: 1,
                    onTap: () {
                      hindEmoji();
                    },
                  ),
                ),
              ),
            ),
            IconButton(
                onPressed: () {
                  hindKeyBoarder();
                  setState(() {
                    emojiShowing = !emojiShowing;
                  });
                },
                icon: Icon(
                  Icons.sentiment_satisfied_alt,
                  size: 30,
                )),
            InkWell(
              child: Container(
                width: 60,
                height: 36,
                decoration: new BoxDecoration(
                    borderRadius: new BorderRadius.circular((5.0)),
                    color: Colors.blue),
                child: Center(
                  child: Text(
                    "发送",
                    style: TextStyle(fontSize: 16, color: Colors.white),
                  ),
                ),
              ),
              onTap: () {
                if (_contentController.text.length != 0) {
                  if (widget.id != "9") {
                    addRecord(_contentController.text);
                  } else {
                    Fluttertoast.showToast(msg: "无法给系统发送消息！");
                  }
                }
              },
            ),
            SizedBox(
              width: 10.0,
            )
          ],
        ),
        Offstage(
          offstage: !emojiShowing,
          child: SizedBox(
            height: 250,
            child: EmojiPicker(
                onEmojiSelected: (Category category, Emoji emoji) {
                  _onEmojiSelected(emoji);
                },
                onBackspacePressed: _onBackspacePressed,
                config: const Config(
                    columns: 7,
                    emojiSizeMax: 32.0,
                    verticalSpacing: 0,
                    horizontalSpacing: 0,
                    initCategory: Category.RECENT,
                    bgColor: Color(0xFFF2F2F2),
                    indicatorColor: Colors.blue,
                    iconColor: Colors.grey,
                    iconColorSelected: Colors.blue,
                    progressIndicatorColor: Colors.blue,
                    backspaceColor: Colors.blue,
                    showRecentsTab: true,
                    recentsLimit: 28,
                    noRecentsText: 'No Recents',
                    noRecentsStyle:
                        TextStyle(fontSize: 20, color: Colors.black26),
                    categoryIcons: CategoryIcons(),
                    buttonMode: ButtonMode.MATERIAL)),
          ),
        ),
      ],
    );
  }
}
